<template>
  <div class="checkups-list">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>体检记录管理</h2>
          <div>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0" v-if="authStore.userRole !== '用户'">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button type="primary" @click="handleAdd" v-if="authStore.userRole !== '用户'">
              <el-icon><Plus /></el-icon>
              添加体检记录
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="宠物编号">
          <el-input v-model="queryForm.petId" placeholder="请输入宠物编号" clearable />
        </el-form-item>
        <el-form-item label="体检日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" v-if="authStore.userRole !== '用户'" />
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ getIndex($index) }}
          </template>
        </el-table-column>
        <el-table-column prop="petId" label="宠物编号" width="100" />
        <el-table-column prop="checkupDate" label="体检日期" width="120" />
        <el-table-column prop="weight" label="体重(kg)" width="100" />
        <el-table-column prop="temperature" label="体温(°C)" width="100" />
        <el-table-column prop="testsperformed" label="检查项目" min-width="180" show-overflow-tooltip />
        <el-table-column prop="checkupsResults" label="检查结果" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" v-if="authStore.userRole !== '用户'">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { checkupsApi } from '@/api'
import type { Checkups, CheckupsQuery } from '@/types'
import { handlePageResponse } from '@/utils/pagination'

const router = useRouter()
const authStore = useAuthStore()

// 查询表单
const queryForm = reactive<Omit<CheckupsQuery, 'pageNum' | 'pageSize'>>({
  petId: undefined,
  checkupDateStart: '',
  checkupDateEnd: ''
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 表格数据
const tableData = ref<Checkups[]>([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 选择行变化
const selectedRows = ref<Checkups[]>([])

// 计算序号
const getIndex = (index: number) => {
  return (pagination.current - 1) * pagination.size + index + 1
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params: CheckupsQuery = {
      ...queryForm,
      pageNum: pagination.current,
      pageSize: pagination.size
    }
    
    // 移除日期范围参数，不在后端查询中使用
    delete params.checkupDateStart
    delete params.checkupDateEnd
    
    console.log('体检记录查询参数:', params)
    const response = await checkupsApi.getPage(params)
    const pageData = handlePageResponse<Checkups>(response)
    
    // 在前端根据日期范围过滤数据
    let filteredData = pageData.records
    if (queryForm.checkupDateStart && queryForm.checkupDateEnd) {
      const startDate = new Date(queryForm.checkupDateStart)
      const endDate = new Date(queryForm.checkupDateEnd)
      
      filteredData = pageData.records.filter(record => {
        if (!record.checkupDate) return false
        const recordDate = new Date(record.checkupDate)
        return recordDate >= startDate && recordDate <= endDate
      })
    }
    
    tableData.value = filteredData
    pagination.total = pageData.total // 使用后端返回的总数
    pagination.current = pageData.current
    pagination.size = pageData.size
  } catch (error) {
    console.error('获取体检记录列表失败:', error)
    ElMessage.error('获取体检记录列表失败')
  } finally {
    loading.value = false
  }
}

// 日期范围改变
const handleDateChange = (dates: [string, string] | null) => {
  if (dates) {
    queryForm.checkupDateStart = dates[0]
    queryForm.checkupDateEnd = dates[1]
  } else {
    queryForm.checkupDateStart = ''
    queryForm.checkupDateEnd = ''
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    petId: undefined,
    checkupDateStart: '',
    checkupDateEnd: ''
  })
  dateRange.value = null
  pagination.current = 1
  fetchData()
}

// 添加
const handleAdd = () => {
  router.push('/checkups/add')
}

// 编辑
const handleEdit = (row: Checkups) => {
  router.push(`/checkups/update/${row.checkupId}`)
}

// 选择行变化
const handleSelectionChange = (rows: Checkups[]) => {
  selectedRows.value = rows
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条体检记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.checkupId).filter((id): id is number => id !== undefined)
    const response = await checkupsApi.delete(ids)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 修改单个删除方法
const handleDelete = async (row: Checkups) => {
  try {
    await ElMessageBox.confirm(`确定要删除体检记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await checkupsApi.delete([row.checkupId!])
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.checkups-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 